package com.mtw.bbs.article.controller.open;




import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.pojo.elasticsearch.TopicESIndex;
import com.mtw.bbs.article.pojo.entity.TopicIndex;
import com.mtw.bbs.article.pojo.vo.*;
import com.mtw.bbs.article.service.TopicMemberService;
import com.mtw.bbs.article.service.TopicIndexService;
import com.mtw.bbs.article.service.TopicTypeService;
import com.mtw.bbs.common.core.constant.ServiceConstant;
import com.mtw.bbs.common.core.constant.SysConstant;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.web.bind.annotation.*;
import java.util.List;


/**
 * 开放话题接口层
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("open/topic")
public class OpenTopicController {

    private final UserClient userClient;
    private final TopicTypeService topicTypeService;
    private final TopicIndexService topicIndexService;
    private final TopicMemberService topicMemberService;
    private final ElasticsearchTemplate elasticsearchTemplate;




    /**
     * 获取所有启用的话题分类
     */
    @GetMapping("/type")
    public Result getAllList() {

        List<TopicTypeVo> list = topicTypeService.getAllEnableType();
        return Result.success(list);
    }




    /**
     * 话题列表
     *
     * @param page 当前页
     * @param size 分页大小
     * @param typeId 话题分类id
     */
    @GetMapping("/index")
    public Result getTopicPage(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "typeId",required = false) String typeId) {

        QueryWrapper<TopicIndex> lqw = new QueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(typeId), "t.type_id", typeId);
        lqw.eq("t.status", ServiceConstant.STATUS_ENABLE);
        lqw.orderByDesc("t.created_date");
        Page<TopicVo> voPage = topicIndexService.getTopicVoPage(page, size, lqw);
        return Result.success(voPage);
    }





    /**
     * 搜索话题
     *
     * @param page 当前页
     * @param size 分页大小
     */
    @GetMapping("/search")
    public Result selectTopic(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "keyword",required = false) String keyword) {

        if (StringUtils.isBlank(keyword)) {
            QueryWrapper<TopicIndex> lqw = new QueryWrapper<>();
            lqw.eq("t.status", ServiceConstant.STATUS_ENABLE);
            lqw.orderByDesc("t.created_date");
            Page<TopicVo> voPage = topicIndexService.getTopicVoPage(page, size, lqw);
            return Result.success(voPage);
        }

        // 查询构建
        NativeQueryBuilder builder = new NativeQueryBuilder();
        builder.withQuery(q -> q.match(m -> m.field("name").query(keyword)));
        builder.withFilter(q -> q.bool( b -> b.must(m -> m.term(t -> t.field("status").value(SysConstant.DEFAULT_ENABLE)))));
        builder.withPageable(PageRequest.of(page - 1, size));

        // es搜索结果
        SearchHits<TopicESIndex> search = elasticsearchTemplate.search(builder.build(), TopicESIndex.class);
        // 无命中的数据
        if (!search.hasSearchHits()) {
            return Result.success(new Page<>(page, size, 0));
        }

        Page<TopicVo> voPage = new Page<>(page, size, search.getTotalHits());

        // 设置结果
        List<TopicVo> collect = search.getSearchHits().stream().map(x -> {
            TopicVo vo = new TopicVo();
            TopicESIndex content = x.getContent();
            BeanUtils.copyProperties(content, vo);
            return vo;
        }).toList();

        topicIndexService.setCoverUrl(collect);
        voPage.setRecords(collect);

        return Result.success(voPage);
    }




    /**
     * 获取话题详细信息
     *
     * @param id 话题id
     */
    @GetMapping("/info/{id}")
    public Result topicInfo(@PathVariable("id") String id) {

        TopicVo info = topicIndexService.getTopicInfoWithMember(id);
        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details != null){
            Integer type = topicMemberService.userJoinedTopic(details.getId(), id);
            info.setJoined(type >= 0);
            info.setMemberType(type);
        }
        return Result.success(info);
    }


    /**
     * 获取简单话题信息
     *
     * @param id 话题id
     */
    @GetMapping("/simpleInfo/{id}")
    public Result simpleTopicInfo(@PathVariable("id") String id) {

        TopicVo info = topicIndexService.getTopicInfo(id);
        return Result.success(info);
    }



    /**
     * 分页获取话题成员
     *
     * @param page   当前页
     * @param size   分页大小
     */
    @GetMapping("/memberList")
    public Result getMemberList(@RequestParam(name = "page") int page,
                               @RequestParam(name = "size") int size,
                               @RequestParam(name = "topicId") String topicId) {

        Page<TopicMemberVo> voPage = topicMemberService.getTopicMemberPage(page, size, topicId);
        return Result.success(voPage);
    }





    /**
     * 获取用户已加入的话题
     *
     * @param username 用户名
     */
    @GetMapping("/user/joinedList/{username}")
    public Result getUserJoinedTopic(@PathVariable("username") String username) {

        Result<UserDto> userinfo = userClient.getUserInfoByUsername(username);
        if (userinfo.isFail() || userinfo.getData() == null) {
            return Result.fail("用户不存在");
        }

        Page<UserTopicVo> voPage = topicIndexService.getUserJoinTopicVoPage(1, 5, false, userinfo.getData().getId());
        return Result.success(voPage);
    }






}
